﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using AvalonDock.Layout;
using CommonControlLibrary;
using Microsoft.Windows.Controls.Ribbon;
using QueryResource.ViewModel;
using SimpleControlLibrary.ViewModel;
using BaseControlLibrary;
using AvalonDock.Layout;
using SimpleControlLibrary.UI;
using DBAccessLibrary.Model;
using System.IO;
using SimpleControlLibrary.Common;
using System.Threading.Tasks;
using CommonControlLibrary.Common;
using QueryResource.Common;

namespace SimpleControlLibrary
{
    /// <summary>
    /// Interaction logic for NewMainWindow.xaml
    /// </summary>
    public partial class NewMainWindow : RibbonWindow
    {
        //主界面
        public MainViewModel ViewModel { get; set; }
        //树
        public DBTreeViewModel TreeViewModel { get; set; }

        public NewMainWindow(ISplash sp)
        {
            sp.SetProgress(50, "正在加载控件……");
            InitializeComponent();
            //this.Closed += MainWindowClosed;
            //this.Loaded += (o, e) =>
            //                   {
            sp.SetProgress(80, "正在初始化数据……");
            Init();
            sp.SetProgress(100, "加载完成……");
            sp.CloseSplash();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void Init()
        {

            ViewModel = new MainViewModel(this.dbtreeview.ViewModel);
            TreeViewModel = this.dbtreeview.ViewModel;
            DataContext = this;

            ViewModel.GetActiveSqlControl = GetActiveSqlControl;
            ViewModel.GetActiveSqlPanel += GetActiveSqlControl;
            ViewModel.ShowNewWindowLoadFile = ShowNewWindowLoadFile;

            TreeViewModel.AppendSqlAction = ShowSql;
            TreeViewModel.AppendLogAction = ShowLog;
            TreeViewModel.AppendWindow = (caption, content) => ShowNewWindowLoadFile(caption, content, false);
            TreeViewModel.AppendDBInfo = ShowDBInfo;
            TreeViewModel.AppendFieldCaption = ShowFieldCaption;
            TreeViewModel.AppendSqlContent = ShowNewWindowLoadFile;

            this.sqlcontrol.ViewModel.AppendLogAction = ShowLog;
            this.sqlcontrol.ViewModel.AppendDataAction = ShowDs;

            this.gridviewcontrol.ViewModel.AppendLogAction = ShowLog;
            this.gridviewcontrol.AppendDataSucess = ShowDataSucess;
            this.gridviewcontrol.ViewModel.AppendSqlContent = ShowNewWindowLoadFile;


            //初始化
            this.dbtreeview.Init();
            this.dbtreeview.ViewModel.ShowDescriptionWindows = entity =>
            {
                AddDescriptionWindow win =
                    new AddDescriptionWindow(entity);
                win.ShowDialog();
            };

            this.sqlcontrol.Init(true);
            this.sqlcontrol.ChangeContentAction = SqlControlContentChange;

            if (Directory.Exists(System.AppDomain.CurrentDomain.BaseDirectory + "\\Temporary"))
            {
                foreach (string file in Directory.GetFiles(System.AppDomain.CurrentDomain.BaseDirectory + "\\Temporary", "*.txt"))
                {
                    ShowNewWindowLoadFile(System.IO.Path.GetFileName(file), File.ReadAllText(file), false);
                }
            }

            UpdateTip();

        }

        private void SqlControlContentChange(object tag, bool isChange)
        {
            LayoutDocument dp = tag as LayoutDocument;
            if (dp != null)
            {
                if (isChange)
                {
                    bool isNotChange = dp.Title.IndexOf('*') < 0;
                    if (isNotChange)
                    {
                        dp.Title += "*";
                    }
                }
                else
                {
                    dp.Title = dp.Title.Replace("*", "");
                }
            }
        }
        /// <summary>
        /// 获取更新信息
        /// </summary>
        private void UpdateTip()
        {
            Func<string> action = () =>
            {
                System.Reflection.AssemblyName name = System.Reflection.AssemblyName.GetAssemblyName(System.Reflection.Assembly.GetExecutingAssembly().Location);

                try
                {
                    if (UpdateHelper.IsDown(name.Version.ToString(), System.IO.Path.GetFileName(name.CodeBase)))
                    {
                        return "亲，又有新版本了，请记得更新哦。";
                    }
                    return "当前版本:" + name.Version;
                }
                catch
                {
                    return "当前版本:" + name.Version;
                }
            };
            Task<string>.Factory.FromAsync(action.BeginInvoke, action.EndInvoke, null)
                .ContinueWith(t => this.lbUpdateInfo.InvokeEx(() =>
                {
                    this.lbUpdateInfo.Text = t.Result;
                }));
        }

        /// <summary>
        /// 获取当前激活的SQL编辑框
        /// </summary>
        /// <returns></returns>
        private SQLControl GetActiveSqlControl()
        {
            SQLControl sql;
            GetActiveSqlControl(out sql);
            return sql;
        }

        private void ActionLayoutPanel(LayoutContent item)
        {
            if (item != null && !item.IsActive)
            {
                this.dockManager.ActiveContent = item;
            }
        }
        /// <summary>
        /// 获得当前激活的 Document
        /// </summary>
        /// <returns></returns>
        private LayoutDocument GetActiveSqlControl(out SQLControl control)
        {
            LayoutDocumentPane layoutDocumentPane = this.documentSQL.Parent as LayoutDocumentPane;
            if (layoutDocumentPane != null)
            {
                var collection = layoutDocumentPane.Children;
                if (collection.Count == 1)
                {
                    LayoutDocument panel = collection[0] as LayoutDocument;
                    if (panel != null)
                    {
                        SQLControl sqlControl = panel.Content as SQLControl;
                        if (sqlControl != null)
                        {
                            control = sqlControl;
                            return panel;
                        }
                    }
                }
                else
                {
                    foreach (LayoutDocument panel in collection)
                    {
                        if (!panel.IsActive)
                            continue;
                        SQLControl sqlControl = panel.Content as SQLControl;
                        if (sqlControl == null) continue;
                        control = sqlControl;
                        return panel;
                    }
                }
            }
            control = this.sqlcontrol;
            return this.documentSQL;
        }
        private GridViewControl GetNoBusyGridControl(bool isActive)
        {
            LayoutAnchorablePane group = this.documentDS.Parent as LayoutAnchorablePane;
            GridViewControl gc = null;
            if (group != null)
            {
                List<LayoutAnchorable> removes = new List<LayoutAnchorable>();
                foreach (LayoutAnchorable panel in group.Children)
                {
                    GridViewControl gridcontrol = panel.Content as GridViewControl;
                    if (gridcontrol != null)
                    {
                        if (!gridcontrol.ViewModel.IsBusy)
                        {
                            if (isActive)
                            {
                                ActionLayoutPanel(panel);
                            }
                            if (gc != null)
                            {
                                removes.Add(panel);
                            }
                            else
                            {
                                gc = gridcontrol;
                            }
                        }
                    }
                }
                removes.ForEach(o => group.Children.Remove(o));
            }
            return gc;
        }
        private void ShowNewWindowLoadFile(string title, string content, bool isFile)
        {
            LayoutDocument panel = new LayoutDocument();
            if (documentGroup.Children.FirstOrDefault(o => o.Title == title) != null)
            {
                panel.Title = title + new Random().Next(5, 9);
            }
            else
            {
                panel.Title = title;
            }

            SQLControl control = new SQLControl { ViewModel = { AppendLogAction = ShowLog, AppendDataAction = ShowDs }, Tag = panel };

            panel.Content = control;
            control.ChangeContentAction = SqlControlContentChange;

            this.documentGroup.Children.Add(panel);

            ActionLayoutPanel(panel);
            if (isFile)
            {
                control.Init(false);
                control.LoadFile(content);
            }
            else
            {
                control.Init(false, false);
                control.IsNewDocument = true;
                control.FilePath = title;
                control.LoadText(content);
            }

            SendKeys.Press(Key.Up);


        }
        private void ShowSql(string sql, SqlControlStatus status)
        {
            //if (!this.documentSQL.IsActive)
            //{
            //    ActionLayoutPanel(documentSQL);
            //}
            //this.sqlcontrol.ViewModel.ExecAppendCmd(sql, isRun, isNewLine);

            SQLControl control;
            GetActiveSqlControl(out control);
            if (control != null)
            {
                control.ViewModel.ExecAppendCmd(sql, status);
            }
        }

        private void ShowLog(string msg, Color errorColor)
        {
            if (errorColor != Colors.Black)
            {
                this.InvokeEx(() =>
                {
                    if (!this.documentLog.IsActive)
                    {
                        ActionLayoutPanel(documentLog);
                    }
                });
            }
            this.logcontrol.ScrollToEnd();
            this.logcontrol.WriteLog(msg, errorColor);
        }

        private void ShowDs(string sql)
        {
            this.BeginInvokeEx(() =>
            {
                GridViewControl control = GetNoBusyGridControl(true);
                if (control != null)
                {
                    control.DataBind(sql);
                }
                else
                {
                    LayoutAnchorablePane group = this.documentDS.Parent as LayoutAnchorablePane;
                    if (@group == null)
                    {
                        GridViewControl gridcontrol = documentDS.Content as GridViewControl;
                        if (gridcontrol != null && gridcontrol.ViewModel.IsBusy)
                        {
                            ShowLog("正在查询中……", Colors.Blue);
                        }
                        else
                        {
                            if (gridcontrol != null)
                                gridcontrol.DataBind(sql);
                        }
                    }
                    else
                    {
                        ////新增一个窗体
                        LayoutAnchorable panel = new LayoutAnchorable { Title = "数据" };

                        control = new GridViewControl
                        {
                            AppendDataSucess = ShowDataSucess
                        };
                        control.ViewModel.AppendLogAction = ShowLog;
                        control.ViewModel.AppendSqlContent = ShowNewWindowLoadFile;

                        panel.Content = control;
                        @group.Children.Add(panel);
                        ActionLayoutPanel(panel);
                        control.DataBind(sql);
                    }
                }
            });
        }

        private void ShowDBInfo(string ip, string dbname, string userid)
        {
            this.BeginInvokeEx(() =>
            {
                this.lbIPname.Text = "数据库IP：" + ip;
                this.lbDBname.Text = string.Format("数据库名称:{0}", dbname.Replace("_", "__"));
                this.lbUserId.Text = "当前用户:" + userid;
            });
        }

        private void ShowFieldCaption(string caption)
        {
            this.lbFieldName.BeginInvokeEx(() =>
            {
                this.lbFieldName.Text = "说明：" + caption;
            });
        }

        private void ShowDataSucess(GridViewControl control)
        {
            LayoutPanel panel = control.Tag as LayoutPanel;
            if (panel != null)
            {
                this.dockManager.ActiveContent = panel;
            }
        }



        private void OpenCommandBindingExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            ViewModel.FileOpenCommand.Execute(null);
        }

        private void RunCommandBindingExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            ViewModel.RunSqlExecuted();
        }

        private void RunCommandBindingCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (ViewModel == null)
                return;
            e.CanExecute = ViewModel.RunSqlCanExecute();
        }

        private void SaveCommandBindingExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            ViewModel.FileSaveCommand.Execute(null);
        }

        private void SaveCommandBindingCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (ViewModel == null)
                return;
            e.CanExecute = ViewModel.FileSaveCommand.CanExecute(null);
        }
        //拷贝字段名
        private void CopyFieldName_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            ViewModel.CopyFieldNameExecuted();
        }

        //删除数据源
        private void DelDB_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            TreeViewModel.DeleteCommand.Execute(TreeViewModel.SelectedItem);
        }
        private void DelDB_CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = TreeViewModel != null && TreeViewModel.DeleteCommand.CanExecute(null);
        }

        //连接
        private void ConnectionDB_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            TreeViewModel.ConnectDBCommand.Execute(TreeViewModel.SelectedItem);
        }
        private void ConnectionDB_CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = TreeViewModel != null && TreeViewModel.ConnectDBCommand.CanExecute(null);
        }

        //断开连接
        private void UnConnectionDB_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            TreeViewModel.UnConnectDBCommand.Execute(TreeViewModel.SelectedItem);
        }
        private void UnConnectionDB_CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = TreeViewModel != null && TreeViewModel.UnConnectDBCommand.CanExecute(null);
        }

        //清空
        private void TxtClear_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            ViewModel.ClearCommand.Execute(null);
        }
        private void TxtClear_CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = TreeViewModel != null && ViewModel.ClearCommand.CanExecute(null);
        }

        //注释
        private void Comment_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            //LayoutPanel panel = GetDocumentControl();
            //SQLControl control = panel.Content as SQLControl;
            //if (control != null)
            //    control.Comment_CommandBinding_Executed(null, null);
        }
        //取消注释
        private void NoComment_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            //LayoutPanel panel = GetDocumentControl();
            //SQLControl control = panel.Content as SQLControl;
            //if (control != null)
            //    control.NoComment_CommandBinding_Excuted(null, null);
        }






        private void DockManagerDocumentClosing(object sender, AvalonDock.DocumentClosingEventArgs e)
        {
            LayoutDocument document = e.Document;

            SQLControl sql = document.Content as SQLControl;
            if (sql != null)
            {
                sql.ViewModel.AppendLogAction = null;
                sql.ViewModel.AppendDataAction = null;
                sql.ViewModel = null;
                sql.RemoveFile();

            }
        }
        void MainWindowClosed(object sender, EventArgs e)
        {
            SaveDocumentContent();
            Application.Current.Shutdown(-1);
        }

        public void SaveDocumentContent()
        {
            LayoutDocumentPane layoutDocumentPane = this.documentSQL.Parent as LayoutDocumentPane;
            if (layoutDocumentPane != null)
                foreach (LayoutDocument panel in layoutDocumentPane.Children)
                {
                    if (panel.Content is SQLControl)
                    {
                        SQLControl sql = panel.Content as SQLControl;
                        if (sql.IsNewDocument)
                        {
                            string fileName = string.Empty;
                            if (panel.Title.IndexOf('*') > 0)
                            {
                                fileName = panel.Title.Replace("*", "");
                                if (fileName != "文档")
                                {
                                    fileName = "Temporary\\" + fileName;
                                }
                                sql.SaveFile(fileName);
                            }
                        }
                        else
                        {
                            //文件
                            if (File.Exists(sql.FilePath))
                            {
                                sql.SaveFile(sql.FilePath);
                            }
                        }
                    }
                }
        }

        private void BtnVerition_Click(object sender, RoutedEventArgs e)
        {
            if (BtnVerition.Label.ToString() == "DEV模式")
            {
                XmlHelper.Instance.IsSimpleControl = true;
                BtnVerition.Label = "原生模式";
            }
            else
            {
                XmlHelper.Instance.IsSimpleControl = false;
                BtnVerition.Label = "DEV模式";
            }
            MessageBoxHelper.Show("重启程序才会生效");
        }

        private void Minimize_Click(object sender, RoutedEventArgs e)
        {
            if (Ribbon.IsMinimized == false)
            {
                Ribbon.IsMinimized = true;
            }
            else
            {
                Ribbon.IsMinimized = false;
            }
        }
    }
}
